package com.lorenzogao.pley.ui.di.moduel

import android.app.Application
import com.google.gson.Gson
import com.lorenzogao.pley.common.http.CommonParamsInterceptor
import com.lorenzogao.pley.common.rx.RxErrorHandler
import com.lorenzogao.pley.ui.data.http.ApiService
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * 作者：Lorenzo Gao
 * Date: 2017/12/27
 * Time: 14:49
 * 邮箱：2508719070@qq.com
 * Description:
 */
@Module
class HttpModule {


    @Provides
    @Singleton
    fun ProvidesOkHttpClient(appApplication: Application, gson: Gson): OkHttpClient {
//        var logging = HttpLoggingInterceptor()
//        logging.level = HttpLoggingInterceptor.Level.BODY

        return OkHttpClient.Builder()
                .addInterceptor(CommonParamsInterceptor(gson,appApplication))
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build()
    }


    @Provides
    @Singleton
    fun ProvidesRetrofit(okHttpClient: OkHttpClient): Retrofit {
        var builder = Retrofit.Builder()
                .baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)

        return builder.build()
    }

    @Provides
    @Singleton
    fun ProvidesApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    @Provides
    @Singleton
    fun providesRxErrorHandler(appApplication: Application): RxErrorHandler {
        return RxErrorHandler(appApplication)
    }


}